package com.repair.gateway.service;

import cn.dev33.satoken.stp.StpInterface;
import com.repair.api.user.constant.UserPermissionEnum;
import com.repair.api.user.constant.UserStateEnum;
import com.repair.api.user.response.data.UserInfo;
import com.repair.api.worker.constant.WorkerPermissionEnum;
import com.repair.api.worker.constant.WorkerStateEnum;
import com.repair.api.worker.response.data.WorkerInfo;
import com.repair.gateway.utils.StpKit;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chunyu
 * @since 2024/10/2,15:15
 * 自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        if (loginType.equals(StpKit.USER.getLoginType())) {
            return getUserPermissions(loginId);
        } else if (loginType.equals(StpKit.WORKER.getLoginType())) {
            // 返回此 loginId 拥有的权限列表
            WorkerInfo workerInfo = (WorkerInfo) StpKit.WORKER.getSessionByLoginId(loginId).get(String.valueOf(loginId));
            return getWorkerPermissions(workerInfo);
        }
        return null;
    }

    private static ArrayList<String> getUserPermissions(Object loginId) {
        // 返回此 loginId 拥有的权限列表
        UserInfo userInfo = (UserInfo) StpKit.USER.getSessionByLoginId(loginId).get(String.valueOf(loginId));
        String state = userInfo.getState();
        ArrayList<String> list = new ArrayList<>();
        // 单纯登录 未实名
        if (state.equals(UserStateEnum.INIT.name())) {
            list.add(UserPermissionEnum.LOGIN.name());
        }
        // 拉黑
        if (state.equals(UserStateEnum.BLOCK.name())) {
            list.add(UserPermissionEnum.BLOCK.name());
        }
        // 实名
        if (state.equals(UserStateEnum.AUTH.name())) {
            list.add(UserPermissionEnum.AUTH.name());
        }
        return list;
    }

    private static ArrayList<String> getWorkerPermissions(WorkerInfo workerInfo) {
        // 实名
        Integer auth = workerInfo.getAuthenticationStatus();
        // 拉黑
        String state = workerInfo.getWorkerStatus();

        ArrayList<String> list = new ArrayList<>();
        // 登录实名
        if (auth == 1) {
            list.add(WorkerPermissionEnum.AUTH.name());
        }
        // 拉黑
        if (state.equals(WorkerStateEnum.BLOCKED.name())) {
            list.add(WorkerPermissionEnum.BLOCK.name());
        } else if (state.equals(WorkerStateEnum.INIT.name())) {
            list.add(WorkerPermissionEnum.LOGIN.name());
        }
        return list;
    }

    /**
     * 后台没用saToken所以暂时不需要
     * @param loginId  账号id
     * @param loginType 账号类型
     * @return
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表
        return null;
    }

}
